package com.cash.lemoloan.statisticlib.Utils;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.text.TextUtils;


import com.cash.lemoloan.statisticlib.OnWiFiListListener;
import com.cash.lemoloan.statisticlib.model.StatisticRouterInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * wifi 接收者
 */
public class WiFiBroadcastReceiver extends BroadcastReceiver {
    private WifiManager mWiFiManager;
    private List<ScanResult> mScanResult;

    private List<StatisticRouterInfo> mRoutersInDifferentChannel;
    private OnWiFiListListener mOnWiFiListListener;

    public WiFiBroadcastReceiver(WifiManager wifiManager, OnWiFiListListener onWiFiListListener) {
        mWiFiManager = wifiManager;
        mOnWiFiListListener = onWiFiListListener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())
                && mWiFiManager != null) {
            mScanResult = mWiFiManager.getScanResults();
            if (mScanResult != null) {
                mRoutersInDifferentChannel = new ArrayList<>();

                for (ScanResult scanResult : mScanResult) {
                    StatisticRouterInfo routerInfo = new StatisticRouterInfo();
                    String capabilities = scanResult.capabilities;
                    String security = "无";
                    if (!TextUtils.isEmpty(capabilities)) {
                        if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
                            security = "WPA";
                        } else if (capabilities.contains("WEP")
                                || capabilities.contains("wep")) {
                            security = "WEP";
                        } else {
                            security = "无";
                        }
                    }
                    routerInfo.setCtime(String.valueOf(System.currentTimeMillis()));
                    routerInfo.setSsid(scanResult.SSID);
                    routerInfo.setMac(scanResult.BSSID);
                    routerInfo.setFrequence(scanResult.frequency);
                    routerInfo.setChannel(DevicesUtil.getChannel(scanResult.frequency));
                    routerInfo.setStrength(WifiManager.calculateSignalLevel(
                            scanResult.level, 5));
                    routerInfo.setSecurity(security);

                    mRoutersInDifferentChannel.add(routerInfo);
                }
            }
        }
        if (mOnWiFiListListener != null) {
            mOnWiFiListListener.onWiFiListResult(mRoutersInDifferentChannel);
        }
    }

}
